package com.fpx.order.plat.web.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
	/**
	 * POST 请求发送
	 * @param data 请求参数
	 * @Param URL 请求地址
	 */
	public static String doHttpPost(String data, String URL) {
		//请求的数据类型
		String dataType="";
		dataType="application/json";
//		dataType="text/xml";
		
		
		System.out.println("发起的数据:" + data);
		byte[] dataArray = data.getBytes();
		InputStream instr = null;
		try {
			URL url = new URL(URL);
			URLConnection http = url.openConnection();
			http.setDoOutput(true);
			http.setDoInput(true);
			http.setUseCaches(false);
			http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			http.setRequestProperty("Content-Type", dataType+";charset=utf-8");
			http.setRequestProperty("Content-length",String.valueOf(dataArray.length));
			System.out.println(String.valueOf("字符长度："+dataArray.length));
			DataOutputStream printout = new DataOutputStream(http.getOutputStream());
			printout.write(dataArray);
			printout.flush();
			printout.close();
			instr = http.getInputStream();
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024*4];
		    int n;
		    while ((n = instr.read(buffer)) != -1) {
		        output.write(buffer, 0, n);
		    }
		    byte[] bis=output.toByteArray();
			String ResponseString = new String(bis, "UTF-8");
			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
				System.out.println("返回空");
			}
			System.out.println("返回数据为:" + ResponseString);
			return ResponseString;
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		} finally {
			try {
				instr.close();
			} catch (Exception ex) {
				return "0";
			}
		}
	}
}
